"""
Market data API routes
"""

from fastapi import APIRouter, HTTPException, Query
from typing import List, Optional
import asyncio

from app.services.market_data import market_data_service
from app.services.indicators import indicator_service

router = APIRouter()


@router.get("/symbols")
async def get_available_symbols(
    exchange: str = Query(default="binance", description="Exchange name")
):
    """Get list of available trading symbols"""
    try:
        symbols = market_data_service.get_available_symbols(exchange)
        return {"symbols": symbols, "exchange": exchange}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/timeframes")
async def get_available_timeframes(
    exchange: str = Query(default="binance", description="Exchange name")
):
    """Get available timeframes"""
    try:
        timeframes = market_data_service.get_timeframes(exchange)
        return {"timeframes": timeframes, "exchange": exchange}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/klines/{symbol}")
async def get_klines(
    symbol: str,
    timeframe: str = Query(default="1h", description="Timeframe"),
    limit: int = Query(default=100, ge=1, le=1000, description="Number of candles"),
    exchange: str = Query(default="binance", description="Exchange name")
):
    """Get kline data for symbol"""
    try:
        data = await market_data_service.fetch_klines(symbol, timeframe, limit, exchange)
        
        # Convert DataFrame to list of dicts
        klines = data.to_dict('records')
        
        return {
            "symbol": symbol,
            "timeframe": timeframe,
            "exchange": exchange,
            "count": len(klines),
            "data": klines
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/price/{symbol}")
async def get_latest_price(
    symbol: str,
    exchange: str = Query(default="binance", description="Exchange name")
):
    """Get latest price for symbol"""
    try:
        price_data = await market_data_service.get_latest_price(symbol, exchange)
        return price_data
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/indicators/{symbol}")
async def get_technical_indicators(
    symbol: str,
    timeframe: str = Query(default="1h", description="Timeframe"),
    limit: int = Query(default=100, ge=50, le=500, description="Number of candles")
):
    """Get technical indicators for symbol"""
    try:
        # Fetch market data
        data = await market_data_service.fetch_klines(symbol, timeframe, limit)
        
        # Calculate indicators
        indicators = indicator_service.calculate_all_indicators(data)
        
        # Get latest values
        latest = indicators.iloc[-1]
        
        # Generate signals
        signals = indicator_service.generate_signals(indicators)
        
        return {
            "symbol": symbol,
            "timeframe": timeframe,
            "latest": {
                "price": latest['close'],
                "sma_20": latest['sma_20'],
                "sma_50": latest['sma_50'],
                "rsi_14": latest['rsi_14'],
                "macd": latest.get('macd', 0),
                "bb_upper": latest.get('bb_upper', 0),
                "bb_lower": latest.get('bb_lower', 0),
                "atr_14": latest['atr_14']
            },
            "signals": signals
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
